package cn.com.cfae.iras.doc.analyze.components.rationality;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 内容合理性
 * M-6
 * 自动提取报告期限,系统时间为本年的4月30日至8月31日之间，最新财报为本年第一季度报表；系统时间为本年的8月31日至10月31日之间，最新财报为本年半年度报表；
 * 系统时间为本年的10月31日至4月30日之间，最新财报为本年三季度报表。
 *
 * 预评/发行阶段
 */
@Component("R1003")
@Scope("prototype")
public class R1003 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(R1003.class);

    @Autowired
    private HandingData handingData;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取R1003组件M");
        //最新财报
        List<ComponentResult> componentResults = checkRulesR1003(getCatalogId(),getCatalogId(),StringUtils.isNotEmpty(getChapterId())?getChapterId():"M-6",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取R1003组件BM");
        List<ComponentResult> componentResults = checkRulesR1003(getCatalogId(),getCatalogId(),StringUtils.isNotEmpty(getChapterId())?getChapterId():"BM-6",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取R1003组件DM");
        List<ComponentResult> componentResults = checkRulesR1003(getCatalogId(),getCatalogId(),StringUtils.isNotEmpty(getChapterId())?getChapterId():"DM-6",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取R1003组件BDM");
        List<ComponentResult> componentResults = checkRulesR1003(getCatalogId(),getCatalogId(),StringUtils.isNotEmpty(getChapterId())?getChapterId():"BDM-6",getRuleTitle());
        return componentResults;
    }


    private List<ComponentResult> checkRulesR1003(String model,String catalogId,String chapterId,String ruleName){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;


        boolean zcfzFlag = false;
        boolean xjllFlag = false;
        boolean lrFlag = false;
        int startPageNum = 0;


        //String jyq = getJYQ();
        String jyq = jyq();

        try {
            if (extractData!=null){

                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPageNum = chapterModel!=null?chapterModel.getStartPage():0;
                if (chapterModel!=null){

                    //资产负债表
                    Map<String, Map<String, ExtractItem>> zcfz = chapterModel.getModel("ZCFZ").getTables();
                    if (isEmptyOfMap(zcfz)){
                        componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-资产负债表","未识别,建议人工核对",true,getRegulationId(),startPageNum,null,"03");
                        componentResults.add(componentResult);
                    }else {

                        for (String key : zcfz.keySet()){
                            if (StringUtils.isNotEmpty(jyq)&&key.equals(jyq)){
                                zcfzFlag = true;
                                break;
                            }
                        }
                        int zcfzPageNum = startPageNum;
                        List<ComponentResult.TextPosition> zcfzContentAndPositionList = null;
                        TextLayout zcfzHead = null;
                        ExtractBizModel zcfzModel = chapterModel.getModel("ZCFZ");
                        if (zcfzModel!=null){
                            zcfzHead =   zcfzModel.getTableNameTextLayout();
                        }

                        if (zcfzHead!=null){
                            zcfzContentAndPositionList = new ArrayList<>();
                            zcfzPageNum = zcfzHead.getPageNumber();
                            zcfzPageNum = zcfzPageNum!=0?zcfzPageNum:startPageNum;
                            ComponentResult.TextPosition contentAndPosition = new ComponentResult().new TextPosition();
                            contentAndPosition.setX(zcfzHead.getLeft());
                            contentAndPosition.setY(zcfzHead.getTop());
                            contentAndPosition.setContent(zcfzHead.getText());
                            zcfzContentAndPositionList.add(contentAndPosition);
                        }
                        if (zcfzFlag){
                            componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-资产负债表","已刷新至最新",false,getRegulationId(),zcfzPageNum,zcfzContentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-资产负债表","建议核对最新财务数据信息",true,getRegulationId(),zcfzPageNum,zcfzContentAndPositionList,"02");
                            componentResults.add(componentResult);
                        }
                    }

                     //现金流量表
                    Map<String, Map<String, ExtractItem>> xjll = chapterModel.getModel("XJLL").getTables();
                    if (isEmptyOfMap(xjll)){
                        componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-现金流量表","未识别,建议人工核对",true,getRegulationId(),startPageNum,null,"03");
                        componentResults.add(componentResult);
                    }else {
                        for (String key : xjll.keySet()){
                            if (StringUtils.isNotEmpty(jyq)&&key.equals(jyq)){
                                xjllFlag = true;
                                break;
                            }

                        }
                        TextLayout zcfzHead = null;
                        int xjllPageNum = startPageNum;
                        List<ComponentResult.TextPosition> xjllContentAndPositionList = null;
                        ExtractBizModel xjllModel = chapterModel.getModel("XJLL");
                        if (xjllModel!=null){
                            zcfzHead = xjllModel.getTableNameTextLayout();
                        }
                        if (zcfzHead!=null){
                            xjllContentAndPositionList = new ArrayList<>();
                            xjllPageNum = zcfzHead.getPageNumber();
                            xjllPageNum = xjllPageNum!=0?xjllPageNum:startPageNum;
                            ComponentResult.TextPosition contentAndPosition = new ComponentResult().new TextPosition();
                            contentAndPosition.setX(zcfzHead.getLeft());
                            contentAndPosition.setY(zcfzHead.getTop());
                            contentAndPosition.setContent(zcfzHead.getText());
                            xjllContentAndPositionList.add(contentAndPosition);
                        }
                        if (xjllFlag){
                            componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-现金流量表","已刷新至最新",false,getRegulationId(),xjllPageNum,xjllContentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-现金流量表","建议核对最新财务数据信息",true,getRegulationId(),xjllPageNum,xjllContentAndPositionList,"02");
                            componentResults.add(componentResult);
                        }
                    }

                    //利润表
                    Map<String, Map<String, ExtractItem>> lr = chapterModel.getModel("LR").getTables();

                    if (isEmptyOfMap(lr)){
                        componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-利润表","未识别,建议人工核对",true,getRegulationId(),startPageNum,null,"03");
                        componentResults.add(componentResult);
                    }else {
                        for (String key : lr.keySet()){
                            if (StringUtils.isNotEmpty(jyq)&&key.equals(jyq)){
                                lrFlag = true;
                                break;
                            }

                        }
                        TextLayout lrHead =null;
                        int lrPageNum = startPageNum;
                        List<ComponentResult.TextPosition> lrContentAndPositionList =null;
                        ExtractBizModel lrModel = chapterModel.getModel("LR");
                        if (lrModel!=null){
                            lrHead = lrModel.getTableNameTextLayout();
                        }
                        if (lrHead!=null){
                            lrContentAndPositionList = new ArrayList<>();
                            lrPageNum = lrHead.getPageNumber();
                            lrPageNum = lrPageNum!=0?lrPageNum:startPageNum;
                            ComponentResult.TextPosition contentAndPosition = new ComponentResult().new TextPosition();
                            contentAndPosition.setX(lrHead.getLeft());
                            contentAndPosition.setY(lrHead.getTop());
                            contentAndPosition.setContent(lrHead.getText());
                            lrContentAndPositionList.add(contentAndPosition);
                        }
                        if (lrFlag){
                            componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-利润表","已刷新至最新",false,getRegulationId(),lrPageNum,lrContentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-利润表","建议核对最新财务数据信息",true,getRegulationId(),lrPageNum,lrContentAndPositionList,"02");
                            componentResults.add(componentResult);
                        }
                    }

                }
            }

        }catch (Exception e){
            String[] ky = new String[]{"资产负债表","现金流量表","利润表"};
            componentResults.clear();
            for (String key:ky){
                componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"最新财报时间检查-"+key,"未识别,建议人工核对",true,getRegulationId(),startPageNum,null,"03");
                componentResults.add(componentResult);
            }
           log.error(e.getMessage(),e);
        }

        return componentResults;
    }


    private boolean isExist(String key){
        String[] jsnjyq = getSNJYQ();
        if (StringUtils.isNotEmpty(key)){
            for (String jyq : jsnjyq){
                if (jyq.equals(key)){
                    return true;
                }
            }
        }
        return false;
    }
    private Boolean isEmptyOfMap(Map<String, Map<String, ExtractItem>> table ){
        if (table==null||table.isEmpty()){
            return true;
        }else {
            for (String key :table.keySet()){
                if (table.get(key)==null||table.get(key).isEmpty()){
                    return true;
                }
                break;
            }
        }
        return false;
    }


    private String jyq(){

        String jyq = null;
        try {

            /**
             * 系统时间为本年的4月30日至8月31日之间，最新财报为本年第一季度报表；
             * 系统时间为本年的8月31日至10月31日之间，最新财报为本年半年度报表；
             * 系统时间为本年的10月31日至4月30日之间，最新财报为本年三季度报表。
             */
            Calendar cal= Calendar.getInstance();

            //获取今年
            int year = cal.get(Calendar.YEAR);

            //获取前年
            cal.add(Calendar.YEAR,-1);
            int beforYear = cal.get(Calendar.YEAR);
            //获取明年
            cal.add(Calendar.YEAR,2);
            int ofterYear = cal.get(Calendar.YEAR);

            //获取当前天，看当前天，在哪个区间

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Date today = calendar.getTime();

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

            Date year0430 = format.parse(year+"0430");
            Date year0831 = format.parse(year+"0831");
            Date year1031 = format.parse(year+"1031");
            Date ofterYear0430 = format.parse(ofterYear+"0430");


            if (today.getTime()>year0430.getTime()&&today.getTime()<=year0831.getTime()){
                jyq =  year+"03";
            }else if (today.getTime()>year0831.getTime()&&today.getTime()<=year1031.getTime()){
                jyq = year+"06";
            }else if (today.getTime()>year1031.getTime()&&today.getTime()<=ofterYear0430.getTime()){
                jyq=  year+"09";
            }else {
                jyq =  beforYear+"09";
            }

        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return  jyq;
    }
}
